<template>
  <ContentWrap>
    <back :backOption="backOption" />
    <div>
      <el-card shadow="never">
        <template #header>
          <span v-if="infoOptions.data.dataType === 'file'">{{
            infoOptions.data.fileName || '--'
          }}</span>
          <span v-else-if="infoOptions.data.dataType === 'column'">{{
            infoOptions.data.column || '--'
          }}</span>
          <span v-else-if="infoOptions.data.dataType === 'table'">{{
            infoOptions.data.table || '--'
          }}</span>
        </template>
        <el-descriptions :column="infoOptions.column">
          <div v-for="(item, index) in infoOptions.columns" :key="index">
            <el-descriptions-item :label="item.label">
              <span v-if="item.key == 'ip'">
                {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
              </span>
              <span v-else-if="item.key == 'source'">
                {{
                  sourceMap.has(infoOptions.data.source)
                    ? sourceMap.get(infoOptions.data.source)
                    : '--'
                }}
              </span>
              <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
            </el-descriptions-item>
          </div>
        </el-descriptions>
      </el-card>
      <el-card class="mt-16px" shadow="never">
        <el-form label-width="100px" ref="formRef" :model="searchValue">
          <el-row>
            <el-col :span="6">
              <el-form-item label="操作人" prop="auditApplyPerson">
                <ns-input
                  v-model="searchValue.auditApplyPerson"
                  clearable
                  placeholder="请输入操作人"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="审核类型" prop="auditType">
                <el-select v-model="searchValue.auditType" clearable placeholder="请选择审核类型">
                  <el-option label="变更审核" value="变更审核" key="1" />
                  <el-option label="新增审核" value="新增审核" key="0" />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="24" class="text-right">
              <el-button @click="searchReset" plain>重置</el-button>
              <el-button @click="search" plain>搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-divider />
        <el-button type="primary" plain @click="merge">对比</el-button>
        <el-button type="primary" plain :disabled="ids.length == 0" @click="delList"
          >删除</el-button
        >
        <AsyncTable
          class="mt-12px"
          ref="tableRef"
          @selection-change="changeTable"
          :fetchData="fetchData"
          v-bind="tableOptions"
        />
      </el-card>
    </div>
  </ContentWrap>
</template>

<script setup lang="tsx">
import { sourceMap } from '@/utils/dict'
import { useRoute } from 'vue-router'
import { getAssetDetail } from '@/api/assetList/index'
import { levelHistoryPage, levelHistoryDeletes } from '@/api/levelHistory'
import { renderClassification, renderLevel } from '@/utils/commonRender'
import dayjs from 'dayjs'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const assetId = ref<string>(route.query.id as string)
const isFormAssetManage = ref<string>(route.query.isFormAssetManage as string)
const dataType = ref<string>(route.query.dataType as string)
const backOption = ref({
  title: '返回'
})
const tableRef = ref()
const formRef = ref()

const infoOptions = reactive({
  column: 5,
  columns: [
    { label: '文件类型', key: 'fileType' },
    { label: '文件大小', key: 'fileSize' },
    { label: '文件来源', key: 'source' },
    { label: '归属系统', key: 'sysName' },
    { label: '归属机构', key: 'deptName' }
  ],
  data: {
    fileName: null,
    fileType: null,
    fileSize: null,
    source: null,
    dataType: null,
    column: null,
    table: null,
    ip: null,
    port: null,
    deptName: null,
    sysName: null,
    columnType: null,
    comment: null,
    schema: null,
    database: null,
    remark: null
  }
})

const tableOptions = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: '操作时间', prop: 'createTime' },
    { label: '操作人', prop: 'auditApplyPerson' },
    { label: '操作内容', prop: 'auditType' },
    {
      label: '操作',
      render: ({ row }) => {
        return (
          <>
            <el-button link type="primary" onClick={() => checkHistory(row)}>
              查看
            </el-button>
          </>
        )
      }
    }
  ],
  data: []
})

const searchValue = ref({
  auditApplyPerson: ''
})

// 搜索重置
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
// 搜索
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
// 表格数据获取
const fetchData = async ({ page, pageSize }) => {
  const { data, count } = await levelHistoryPage({
    page,
    pageSize,
    assetMessageId: assetId.value,
    dataType: dataType.value,
    ...searchValue.value
  })
  return { data, count }
}

const ids = ref<string[]>([])
const chooseItems = ref<any[]>([])
const changeTable = (val) => {
  ids.value = []
  chooseItems.value = []
  val.map((item) => {
    ids.value.push(item.id)
    chooseItems.value.push(item)
  })
}

const openHistory = (row) => {
  proxy?.$Drawer({
    params: {
      id: row.processInstanceId,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `历史记录`,
    size: '60%',
    component: import('@/views/asset/pendingAsset/components/auditRecord.vue')
  })
}
const checkHistory = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `查看分类分级详情`,
    size: '40%',
    component: import('@/views/assetManage/components/baseInfo.vue')
  })
}

const delList = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await levelHistoryDeletes(ids.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    tableRef.value.fetchData()
  } catch {}
}

const merge = () => {
  console.log('chooseItems.value', chooseItems.value)
  let firstItem
  let nextItem
  if (chooseItems.value.length !== 2) {
    message.warning('只能选择两条数据进行比较')
    return
  } else {
    const data1 = chooseItems.value[0]
    const data2 = chooseItems.value[1]

    if (dayjs(data1.createTime).isBefore(dayjs(data2.createTime))) {
      firstItem = data1
      nextItem = data2
    } else {
      firstItem = data2
      nextItem = data1
    }
  }
  proxy?.$Drawer({
    params: {
      tableData: infoOptions.data,
      firstItem, //更早的id
      nextItem,
      isDatabase: 1,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `历史记录对比`,
    size: '60%',
    component: import('@/views/asset/pendingAsset/components/singleChange.vue')
  })
}

const getData = async () => {
  const res = await getAssetDetail({ id: assetId.value })
  infoOptions.data.source = res.data.source
  infoOptions.data.dataType = res.data.dataType
  infoOptions.data.column = res.data.column
  infoOptions.data.table = res.data.table
  infoOptions.data.ip = res.data.ip
  infoOptions.data.port = res.data.port
  infoOptions.data.columnType = res.data.columnType
  infoOptions.data.comment = res.data.comment
  infoOptions.data.schema = res.data.schema
  infoOptions.data.database = res.data.database
  infoOptions.data.remark = res.data.remark
  infoOptions.data.sysName = res.data.sysName
  infoOptions.data.deptName = res.data.deptName
  infoOptions.data.fileType = res.data.fileType
  infoOptions.data.fileSize = res.data.fileSize
  infoOptions.data.fileName = res.data.fileName
}

const controlTopDesc = () => {
  if (dataType.value === 'column') {
    infoOptions.columns = [
      { label: '字段名称：', key: 'column' },
      { label: '字段类型：', key: 'columnType' },
      { label: '字段描述：', key: 'comment' },
      { label: '所属表：', key: 'table' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' }
    ]
  } else if (dataType.value === 'table') {
    infoOptions.columns = [
      { label: '表名称：', key: 'table' },
      { label: '表描述：', key: 'remark' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' }
    ]
  }
}

onMounted(async () => {
  getData()
  controlTopDesc()
})
</script>
